package com.example.aijie.autoreadhelper.widget;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.example.aijie.autoreadhelper.utils.DeviceHelper;
import com.example.aijie.autoreadhelper.utils.LogUtils;

public class DraggableFloatView extends LinearLayout {
    private Context mContext;
    /**
     * 定义浮动窗口布局
     */
    private View mLayout;
    /**
     * 悬浮窗的布局
     */
    private WindowManager.LayoutParams wmParams;
    /**
     * 创建浮动窗口设置布局参数的对象
     */
    private WindowManager mWindowManager;
    /**
     * 触摸监听器
     */
    private GestureDetector mGestureDetector;

    /**
     * 判断悬浮窗是否移动
     */
    private boolean isMove;

    public DraggableFloatView(Context context, OnRootClickListener onRootClickListener) {
        super(context);
        this.mContext = context;
        this.onRootClickListener = onRootClickListener;
    }

    private void init() {
        if (mLayout == null) {
            throw new RuntimeException("mLayout must not be null");
        }
        if (mLayout.getParent() != null) {
            ViewGroup group = (ViewGroup) mLayout.getParent();
            group.removeAllViews();
        }
        mWindowManager = (WindowManager) mContext.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        wmParams = getParams(wmParams);//设置好悬浮窗的参数
        // 添加悬浮窗的视图
        try {
            mWindowManager.updateViewLayout(mLayout, wmParams);
        } catch (IllegalArgumentException e) {
            mWindowManager.addView(mLayout, wmParams);
        }
        //设置触摸事件
        mGestureDetector = new GestureDetector(mContext, new MyOnGestureListener());
        //设置监听器
        mLayout.setOnTouchListener(new FloatingListener());
    }

    public void setView(View view) {
        if (view == null) {
            return;
        }
        this.mLayout = view;
        this.removeAllViews();
        this.addView(view);
    }

    /**
     * 对windowManager进行设置
     *
     * @param wmParams
     * @return
     */
    public WindowManager.LayoutParams getParams(WindowManager.LayoutParams wmParams) {
        wmParams = new WindowManager.LayoutParams();
        //设置window type 下面变量2002是在屏幕区域显示，2003则可以显示在状态栏之上
        //wmParams.type = LayoutParams.TYPE_PHONE;
        //wmParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
//        wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        //wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;
        //设置可以显示在状态栏上
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
//        } else {
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
//        }
        //设置悬浮窗口长宽数据
        wmParams.x = 1020;
        wmParams.y = 984;
        wmParams.width = DeviceHelper.dip2px(mContext, 150f);
        wmParams.height = DeviceHelper.dip2px(mContext, 200f);

        return wmParams;
    }

    /**
     * 自己写的悬浮窗监听器
     */
    private class FloatingListener implements OnTouchListener {
        //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
        private int mTouchStartX, mTouchStartY, mTouchCurrentX, mTouchCurrentY;
        //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
        private int mStartX, mStartY, mStopX, mStopY;

        @Override
        public boolean onTouch(View arg0, MotionEvent event) {

            int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    isMove = false;
                    mTouchStartX = (int) event.getRawX();
                    mTouchStartY = (int) event.getRawY();
                    mStartX = (int) event.getX();
                    mStartY = (int) event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    mTouchCurrentX = (int) event.getRawX();
                    mTouchCurrentY = (int) event.getRawY();
                    wmParams.x += mTouchCurrentX - mTouchStartX;
                    wmParams.y += mTouchCurrentY - mTouchStartY;
                    mWindowManager.updateViewLayout(mLayout, wmParams);

                    mTouchStartX = mTouchCurrentX;
                    mTouchStartY = mTouchCurrentY;
                    break;
                case MotionEvent.ACTION_UP:
                    mStopX = (int) event.getX();
                    mStopY = (int) event.getY();
                    //System.out.println("|X| = "+ Math.abs(mStartX - mStopX));
                    //System.out.println("|Y| = "+ Math.abs(mStartY - mStopY));
                    if (Math.abs(mStartX - mStopX) >= 1 || Math.abs(mStartY - mStopY) >= 1) {
                        isMove = true;
                    }
                    break;
            }
            //此处必须返回false，否则OnClickListener获取不到监听
            return mGestureDetector.onTouchEvent(event);
        }

    }

    /**
     * 自己定义的手势监听类
     */
    class MyOnGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (!isMove) {
                if (onRootClickListener != null) {
                    onRootClickListener.onRootClick();
                }
            }
            return super.onSingleTapConfirmed(e);
        }
    }

    private OnRootClickListener onRootClickListener;

    public interface OnRootClickListener {
        void onRootClick();
    }

    public void show() {
        init();
    }

    public void dismiss() {
        if (mLayout != null && mWindowManager != null) {
            // 移除悬浮窗口
            mWindowManager.removeView(mLayout);
        }
    }
}
